<template>
  <FModal header="人员管理" width="1200" ref="refFModal">
    <FPage>
      <template #header>
        <div style="padding: 5px">
          <el-form inline ref="searchForm" style="height: 30px"
                   class="user-manager-body-search simple-line-form"
                   :model="searchParams">
            <el-form-item prop="username" label="登录名" :rules="[]">
              <el-input placeholder="请输入用户登录名称" style="width: 120px"
                        v-model="searchParams.username"/>
            </el-form-item>

            <el-form-item prop="realname" label="姓名" :rules="[]">
              <el-input placeholder="请输入用户登录名称" style="width: 120px"
                        v-model="searchParams.realname"/>
            </el-form-item>

            <el-form-item prop="containsVicePosition" label="包含副岗" :rules="[]">
              <SystemDict :defaultValue="'1'" style="width: 100px"
                          dict-code="yesOrNot" v-model="searchParams.containsVicePosition"/>
            </el-form-item>

            <el-form-item prop="userStatus" label="状态" :rules="[]">
              <SystemDict dict-code="userStatus" style="width: 100px"
                          v-model="searchParams.userStatus"/>
            </el-form-item>

            <el-form-item style="padding-left: 10px">
              <el-button icon="search" round @click="search"></el-button>
              <el-button icon="clear" round @click="clear"></el-button>
              <el-button icon="add" type="primary" round @click="addNew"></el-button>
              <el-button icon="remove" type="warning" round :disabled="!removeAble" @click="remove"></el-button>
            </el-form-item>
          </el-form>
        </div>
      </template>

      <div class="user-manager-body">
        <div class="user-manager-left">
          <el-tree
              node-key="id" check-on-click-node check-strictly
              :expand-on-click-node="false" show-checkbox @checkChange="checkChange"
              auto-expand-parent ref="refUnitTree" @check="onCheck"
              class="filter-tree" :data="unitTrees" :indent="5"
              :props="defaultProps" default-expand-all @node-click="departSelectChange"
              :filter-node-method="filterNode">
          </el-tree>
        </div>
        <div style="width: 10px"/>
        <div class="user-manager-right">
          <FPage>
            <div style="height: 100%;">
              <el-table height="100%" border stripe :default-sort="sortConfig" @row-click="rowClick"
                        :data="dataSource" @sort-change="sortChange" @selection-change="selectionChange"
                        v-loading="loading">
                <el-table-column type="selection" width="40"/>
                <el-table-column show-overflow-tooltip prop="username" label="登录名"/>
                <el-table-column show-overflow-tooltip prop="realname" label="姓名"/>
                <el-table-column show-overflow-tooltip prop="userStatus" label="状态">
                  <template #default="{row}">
                    <SystemDict :disabled="true" dict-code="userStatus" v-model="row.userStatus"/>
                  </template>
                </el-table-column>
                <el-table-column show-overflow-tooltip prop="positionName" label="主岗"/>
                <el-table-column show-overflow-tooltip prop="positionLevelName" label="职务级别"/>
                <el-table-column show-overflow-tooltip prop="departName" label="所属部门"/>
                <el-table-column show-overflow-tooltip prop="sort" label="排序"/>
              </el-table>
            </div>
            <template #footer>
              <div style="display: flex; padding: 5px; justify-content: end">
                <el-pagination
                    v-model:current-page="pagination.current"
                    v-model:page-size="pagination.size"
                    :page-sizes="pageOptions"
                    background layout="total, sizes, prev, pager, next, jumper"
                    :total="pagination.total" small
                    @size-change="search"
                    @current-change="pageChange"
                />
              </div>
            </template>
          </FPage>
        </div>
      </div>
    </FPage>

    <template #footer>
      <el-button icon="close" type="warning" round @click="close">关闭</el-button>
    </template>
  </FModal>

  <UserEditModal @saved="search" ref="refUserEditModal"/>
</template>
<script setup>
import FModal from '@/components/FModal/index.vue';
import {computed, ref, shallowRef} from 'vue';
import {isEmpty, listToTrees, real, treesForeach} from '@/utils/CommonUtils';
import FPage from '@/components/layout/FPage.vue';
import {deleteAction, getAction} from '@/request/BaseRequest';
import TableSearchUtils from '@/utils/TableSearchUtils';
import UserEditModal from '@/views/system/UnitManagement/UserEditModal/index.vue';
import SystemDict from '@/components/SystemDict/index.vue';
import {ElMessage, ElMessageBox} from 'element-plus';

const refUserEditModal = shallowRef();
const refFModal = shallowRef();
let unitData = undefined;
const departData = shallowRef();
const refUnitTree = shallowRef();
const searchForm = shallowRef();
const unitTrees = shallowRef([]);
const defaultProps = {
  children: 'children',
  label: 'unitName',
};
const searchParams = ref({});

function setData(_unitData) {
  unitData = real(_unitData);
  refFModal.value.open();
  loadUnitsByPath();
}

function close() {
  refFModal.value.close();
}

function loadUnitsByPath(callback) {
  loading.value = true;
  getAction('/sys/unit/loadDepatrsByPath',
      {path: unitData.path}).then(data => {
    loading.value = false;
    if (data.success) {
      let result = data.result;
      setUnitTrees(result);
      if (callback) callback();
      searchForm.value.resetFields();
      search();
    }
  });
}

function setUnitTrees(list) {
  let trees = listToTrees(list);
  if (isEmpty(trees)) {
    trees = [];
  }
  unitTrees.value = trees;
}


function onCheck(data) {
  let node = refUnitTree.value.getCheckedNodes();
  if (!isEmpty(node)) {
    refUnitTree.value.setCheckedKeys([data.id]);
  }
}

function filterNode(value, data) {
  if (!value) return true;
  return data.unitName.includes(value);
}

function checkChange() {
  let nodes = refUnitTree.value.getCheckedNodes();
  if (isEmpty(nodes)) {
    departData.value = undefined;
  } else {
    if (nodes[0].id === unitData.id) {
      departData.value = undefined;
    } else {
      treesForeach(unitTrees.value, node => {
        if (node.id === nodes[0].id) {
          departData.value = node;
        }
      });
    }
  }
  search();
}

function doSearch(params) {
  params = real(params);
  params.unitId = unitData.id;
  if (!isEmpty(departData.value)) {
    params.departId = departData.value.id;
  }

  loading.value = true;
  getAction('/sys/user/searchUsers', params)
  .then(data => {
    loading.value = false;
    if (data.success) {
      let result = data.result;
      setSearchResult(result);
    }
  });
}

function onSelection() {

}

function onRowClick(row) {
  row = real(row);
  refUserEditModal.value.setData(unitData, departData, row);
}

function departSelectChange(node) {
  node = real(node);
  refUnitTree.value.setCheckedKeys([node.id]);
  departData.value = {id: node.id};
}

const removeAble = computed(() => {
  return real(selectedRows).length >= 1;
});

function remove() {
  ElMessageBox.confirm('删除后不可恢复, 确定删除吗', '确定删除?', {
    draggable: true,
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    let ids = real(selectedRows).map(item => item.id);
    loading.value = true;
    deleteAction('/sys/user/removeUsers', {ids: ids.toString()}).then(data => {
      loading.value = false;
      if (data.success) {
        ElMessage({
          message: '删除成功',
          type: 'success',
        });
        search(true);
      }
    });
  }).catch(() => {
  });
}

function addNew() {
  refUserEditModal.value.setData(unitData, departData, undefined);
}

function clear() {
  searchForm.value.resetFields();
}

const {
  loading, rowClick, search, selectionChange, setSearchResult, pageOptions, pageChange,
  sortChange, dataSource, resetQueryParams, sortConfig, selectedRows, pagination
} = TableSearchUtils({
  refForm: searchForm,
  doSearch,
  defaultSortConfig: {
    prop: undefined,
    order: undefined,
  },
  searchParams,
  selectionChange: onSelection,
  rowClick: onRowClick
});

defineExpose({
  search,
  setData,
  departSelectChange
});
</script>
<script>
export default {
  name: 'UserManageModal'
};
</script>
<style>
.user-manager-body {
  display: flex;
}

.user-manager-right {
  flex: 1;
}

.user-manager-right,
.user-manager-left {
  width: 270px;
  height: 100%;
  background: white;
  border: 1px solid #f0f2f5;
  overflow: auto;
  box-sizing: border-box;
}

.f-modal-body .user-manager-body {
  height: 600px;
}

.f-modal-fullscreen-body .user-manager-body {
  height: 100%;
}

.user-manager-body-search label {
  margin: 0;
  padding: 0 5px;
}
</style>
